import { computed } from 'vue';
import { useEditorStore } from '../stores/editor';
import type { HistoryRecord } from '../types/editor';

export function useHistory() {
  const editorStore = useEditorStore();

  const history = computed(() => editorStore.history);
  const historyIndex = computed(() => editorStore.historyIndex);
  const canUndo = computed(() => editorStore.canUndo);
  const canRedo = computed(() => editorStore.canRedo);

  const addHistory = (content: string) => {
    editorStore.addHistory(content);
  };

  const undo = () => {
    editorStore.undo();
    return editorStore.content;
  };

  const redo = () => {
    editorStore.redo();
    return editorStore.content;
  };

  const getHistoryAt = (index: number): HistoryRecord | null => {
    if (index >= 0 && index < history.value.length) {
      return history.value[index];
    }
    return null;
  };

  const getCurrentHistory = (): HistoryRecord | null => {
    return getHistoryAt(historyIndex.value);
  };

  return {
    history,
    historyIndex,
    canUndo,
    canRedo,
    addHistory,
    undo,
    redo,
    getHistoryAt,
    getCurrentHistory
  };
}